package com.growthgate.bootcommon.factory;

import org.jetbrains.annotations.NotNull;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * EnumConverterFactory
 *
 * @author GrowthGate
 * @date 2020/2/24
 */
public class EnumConverterFactory implements ConverterFactory<String, Enum> {

    private static final Map<Class, Converter> CONVERTER_MAP = new WeakHashMap<>();

    @NotNull
    @Override
    @SuppressWarnings("unchecked")
    public <T extends Enum> Converter<String, T> getConverter(@NotNull Class<T> aClass) {
        return CONVERTER_MAP.computeIfAbsent(aClass, enumClass -> new EnumConverter<>(aClass));
    }

    class EnumConverter<E extends Enum<E>> implements Converter<String, E> {

        private E[] enums;
        private Class<E> enumClass;

        public EnumConverter(@NotNull Class<E> enumClass) {
            enums = enumClass.getEnumConstants();
            this.enumClass = enumClass;
        }

        @Override
        public E convert(@NotNull String string) {
            try {
                Integer i = Integer.valueOf(string);
                if (i < 0 || i > enums.length) {
                    throw new IllegalArgumentException("For input string: \"" + string + "\"");
                }
                return enums[i];
            } catch (NumberFormatException e) {
                // 尝试用name转换为枚举
                return Enum.valueOf(enumClass, string);
            }
        }

    }

}